<?php
// +----------------------------------------------------------------------
// | title: 标题注释
// +----------------------------------------------------------------------
// | Author: TZ.Leong
// +----------------------------------------------------------------------
// | Date: 2019/7/19 14:08
// +----------------------------------------------------------------------

namespace app\single\model;


use think\facade\Log;
use think\Model;

class RoleMailModel extends Model
{
    public function initialize()
    {
//        $this->table = config("database.game") . ".role_mail";
        $this->table = "role_mail";

    }

    /**
     * 插入邮件内容
     * @param integer $playerId 玩家ID
     * @param integer $mail_type 邮件类型
     * @param string $attachment 附件
     * @param string $title 邮件标题
     * @param string $content 邮件内容
     * @param bool $truncate 是否直接从邮件表获取最大ID值true-是false-否
     * @return bool|int                   返回一个主键ID
     */
    public function sendMail($playerId, $attachment = "[]", $title, $content, $mail_type, $truncate = false)
    {
        //邮件当前最大ID值
        $mailId = $this->getMaxMailId($truncate);
        //组合邮件插入数据
        $data = array(
            "id" => $mailId,
            "type" => $mail_type,
            "rec_role_id" => $playerId,
            "mail_title" => $title,
            "mail_content" => $content,
            "ctime" => time(),
            "attach" => $attachment,
            "mail_kind" => 1,
        );
        //主键重复容错
        try {
            if ($this->insert($data)) {
                return $mailId;
            }
            return false;
        } catch (\Exception $e) {
            Log::write("insert into role_mail error  " . $e->getMessage(),"error");
            //再次执行插入邮件
            return $this->sendMail($playerId, $attachment, $title, $content, $mail_type, true);
        }
    }

    /**
     * 获取邮件最大ID
     * @param bool $truncate 是否直接从邮件表获取最大ID值true-是false-否
     * @return int
     */
    private function getMaxMailId(bool $truncate = false): int
    {
        $redisKey = "player_mail_max_id";
        $maxId = (int)cache($redisKey);
        if ($maxId <= 0 || $truncate) {
            //获取邮件表id < 200000000的最大值
            $maxId = (int)$this->where("id", "<", 200000000)->max("id");
        }
        $maxId += 1;
        cache($redisKey, $maxId);
        return $maxId;
    }
}